/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.code.motoo.filter;

import com.google.code.motoo.core.IoSession;

/**
 * 
 * @author linfengqi
 * @version 1.0  May 18, 2009
 */
public class DefaultFilterChain implements FilterChain {
	
	private Filter[] filter = new Filter[0];
	private int pos = 0;
	
	public DefaultFilterChain() {
	}
	
	public void doFilter(IoSession session, Object message) throws Exception {
		if (pos < filter.length)
			filter[pos++].doFilter(this, session, message);
		else
			session.getHandler().messageReceived(session, message);
	}
	
	public void addFilter(Filter ioFilter) {
		int currentSize = filter.length;
		Filter[] newFilter = new Filter[currentSize + 1];
		if (currentSize > 0) {
			System.arraycopy(filter, 0, newFilter, 0, currentSize);  
		}
		newFilter[currentSize] = ioFilter;
		filter = newFilter;
	}
	
	public void reuse() {
        pos = 0;
    }
	
}
